/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-11-20
 * Time: 11:22
 */
class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }

public class Solution {
    private int postIndex; //标记后序遍历数组的末尾
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postIndex = postorder.length-1;
        return func(postorder,inorder,0,inorder.length);
    }

    private TreeNode func(int[] postorder, int[] inorder, int inBegin, int inEnd) {
        //递归结束条件
        if (inBegin > inEnd) {
            return null;
        }

        //先获得根结点
        TreeNode root = new TreeNode(postorder[postIndex]);

        //去中序遍历数组中找到根结点的索引
        int rootIndex = findIndex(inorder,inBegin,inEnd,postorder[postIndex]);

        //更新postIndex
        postIndex--;

        //构建右子树
        root.right = func(postorder,inorder,rootIndex+1,inEnd);

        //构建左子树
        root.left = func(postorder,inorder,inBegin,rootIndex-1);

        return root;
    }

    private int findIndex(int[] inorder, int inBegin, int inEnd, int val) {
        for (int i = inBegin; i <= inEnd; i++) {
            if (inorder[i] == val) {
                return i;
            }
        }
        return -1;
    }
}
